package com.codeduck.config;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 读写分离（需要配置Mysql主从复制）
 *
 * @author: codeduck@163.com
 * @since: 2021-06-04
 */
//@Configuration
public class ReadwriteSplittingConfig {

    public DataSource getDataSource() throws SQLException {
//        ReadwriteSplittingDataSourceRuleConfiguration dataSourceConfig = new ReadwriteSplittingDataSourceRuleConfiguration(
//                "demo_read_query_ds", "", "write_ds", Arrays.asList("read_ds_0", "read_ds_1"), null);
//        ReadwriteSplittingRuleConfiguration ruleConfig = new ReadwriteSplittingRuleConfiguration(Collections.singleton(dataSourceConfig), Collections.emptyMap());
//        return ShardingSphereDataSourceFactory.createDataSource(createDataSourceMap(), Collections.singleton(ruleConfig), new Properties());
        return null;
    }

    private static Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> dataSourceMap = new HashMap<>(16);

        // 配置第一个数据源
        HikariDataSource write_ds = new HikariDataSource();
        write_ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        write_ds.setJdbcUrl("jdbc:mysql://192.168.2.123:3306/springboot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8");
        write_ds.setUsername("root");
        write_ds.setPassword("123456");

        // 配置第二个数据源
        HikariDataSource read_ds_0 = new HikariDataSource();
        read_ds_0.setDriverClassName("com.mysql.cj.jdbc.Driver");
        read_ds_0.setJdbcUrl("jdbc:mysql://192.168.2.124:3306/springboot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8");
        read_ds_0.setUsername("root");
        read_ds_0.setPassword("123456");

        HikariDataSource read_ds_1 = new HikariDataSource();
        read_ds_1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        read_ds_1.setJdbcUrl("jdbc:mysql://192.168.2.125:3306/springboot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8");
        read_ds_1.setUsername("root");
        read_ds_1.setPassword("123456");

        dataSourceMap.put("write_ds", write_ds);
        dataSourceMap.put("read_ds_0", read_ds_0);
        dataSourceMap.put("read_ds_1", read_ds_1);
        return dataSourceMap;
    }
}
